<template>
  <div>
    <el-upload
      action="http://mail-yhz.oss-cn-guangzhou.aliyuncs.com"
      :data="dataObj"
      :auto-upload="true"
      list-type="picture-card"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
      :limit="maxCount"
      :on-exceed="handleExceed"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
  </div>
</template>
<script>
import { uploadImgs } from "./policy";
import { getUUID } from "@/utils";
export default {
  name: "multiUpload",
  props: {
    //图片属性数组
    value: Array,
    //最大上传图片数量
    maxCount: {
      type: Number,
      default: 30,
    },
  },
  data() {
    return {
      fileList:[],
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        ossaccessKeyId: "",
        dir: "",
        host: "",
        uuid: "",
      },
      dialogVisible: false,
      dialogImageUrl: null,
    };
  },
  computed: {
    // fileList() {
    //   let fileList = [];
    //   if (this.value) {
    //     for (let i = 0; i < this.value.length; i++) {
    //       fileList.push({ url: this.value[i] });
    //     }
    //   }

    //   return fileList;
    // },
  },
  mounted() {
    uploadImgs()
      .then((response) => {
        this.dataObj.policy = response.data.policy;
        this.dataObj.signature = response.data.signature;
        this.dataObj.ossaccessKeyId = response.data.accessid;
        this.dataObj.dir = response.data.dir;
        this.dataObj.host = response.data.host;
      })
      .catch((err) => {
        console.log("出错了......", err);
      });
  },
  methods: {
    emitInput(fileList) {
      let value = [];
      for (let i = 0; i < fileList.length; i++) {
        value.push(fileList[i].url);
      }
      this.$emit("input", value);
    },
    handleRemove(file, fileList) {
      this.emitInput(fileList);
      this.fileList = fileList
      console.log(fileList);
    },
    handlePreview(file) {
      this.dialogVisible = true;
      this.dialogImageUrl = file.url;
    },
    beforeUpload(file) {
      this.dataObj.key = this.dataObj.dir + getUUID() + "_" + "${filename}";
    },

    handleUploadSuccess(res, file) {
      this.fileList.push({
        name: file.name,
        // url: this.dataObj.host + "/" + this.dataObj.dir + "/" + file.name； 替换${filename}为真正的文件名
        url:
          this.dataObj.host +
          "/" +
          this.dataObj.key.replace("${filename}", file.name),
      });
      this.emitInput(this.fileList);
      console.log(this.fileList);
      
    },
    handleExceed(files, fileList) {
      this.$message({
        message: "最多只能上传" + this.maxCount + "张图片",
        type: "warning",
        duration: 1000,
      });
    },
  },
};
</script>
<style>
</style>


